package com.windfone.web.action;

import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.windfone.common.StringUtil;
import com.windfone.model.Member;
import com.windfone.model.MemberDetail;
import com.windfone.model.Order;
import com.windfone.service.MemberService;

public class RegisterAction extends ActionSupport {
	protected static Logger logger =Logger.getLogger(RegisterAction.class);
	/**	 */
	private static final long serialVersionUID = 1L;
	private MemberService memberService;
	private String name;
	private String cardId;
	private MemberDetail memberDetail;
	private String password;
	private String loginName;
	private String email;
	private String rtvMsg;
	public String getRtvMsg() {
		return rtvMsg;
	}
	public void setRtvMsg(String rtvMsg) {
		this.rtvMsg = rtvMsg;
	}
	public MemberService getMemberService() {
		return memberService;
	}
	public String getName() {
		return name;
	}
	public String getCardId() {
		return cardId;
	}
	public MemberDetail getMemberDetail() {
		return memberDetail;
	}
	public String getPassword() {
		return password;
	}
	public String getLoginName() {
		return loginName;
	}
	public String getEmail() {
		return email;
	}
	public boolean isExistFlag() {
		return existFlag;
	}
	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setCardId(String cardId) {
		this.cardId = cardId;
	}
	public void setMemberDetail(MemberDetail memberDetail) {
		this.memberDetail = memberDetail;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public void setExistFlag(boolean existFlag) {
		this.existFlag = existFlag;
	}
	private boolean existFlag = false;
 
	public String addRegisterUser(){
		rtvMsg = "";
		int flag = 0;
		int flag2 = 0;
		Member m = new Member();
		m.setLoginName(loginName);
		if ( password !=null && !password.equals("")){
			m.setPassword(  StringUtil.encode(password) );
			if ( memberService.checkMember(m)==false)
				flag= memberService.addRegisterUser( m );
		}
		if (flag ==0 ){
			System.out.println("add user register don't success"+loginName );
		}
		if ( flag == 1){
			Member m2 = memberService.getMemberByLoginName(m);
			memberDetail = new MemberDetail();
			memberDetail.setEmail(email);
			memberDetail.setMemberId(m2.getId());
			memberDetail.setSex(-1);
			flag2=memberService.addRegisterDetailUser(memberDetail);
		}
		if ( flag ==1 && flag2==1){
			rtvMsg = "注册成功";
		}
		return SUCCESS;
	}
	
	public String orderRegisterUser(){
		rtvMsg = "";
		int flag = 0;
		int flag2 = 0;
		int jdbcFlag = 0;
		Member m = new Member();
		m.setLoginName(loginName);
		logger.info("  loginName 1:"+loginName);
		try {
		if ( password !=null && !password.equals("")){
			m.setPassword(  StringUtil.encode(password) );
			if ( memberService.checkMember(m)==false ) { //检查是否存在该用户,如果不存在执行以下流程 
				flag= memberService.addRegisterUser( m );//新增用户
				if (flag ==0 ){
					logger.info("add user register don't success"+loginName );
					jdbcFlag = 0;
				}
				else if ( flag == 1){
					logger.info("  loginName 3:");
					String tmp = StringUtil.encode( password );//对密码进行加密
					Member memberBean= memberService.loginByLoginName(loginName, tmp);
			 
					Member m2 = memberService.getMemberByLoginName(m);
					memberDetail = new MemberDetail();
					memberDetail.setEmail(email);
					memberDetail.setMemberId(m2.getId());
					memberDetail.setSex(-1);
					flag2 = memberService.addRegisterDetailUser(memberDetail);
					if ( flag ==1 && flag2 ==1 ){
						rtvMsg = "注册成功";
						jdbcFlag = 1;
					}
					if ( memberBean != null ){
						HttpServletRequest request = ServletActionContext.getRequest();
						HttpSession session = request.getSession();
						session.setAttribute("userBean", memberBean);
						int i=memberService.updateLastLogin(memberBean);
					}
					logger.info("  loginName 4:");
				}
			}
		}
		}catch(Exception e){
			logger.error(e);
		}finally {
			if (  jdbcFlag == 0){
				useJdbcMethod(loginName,password);
			}
		}
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);
		Object sessionObj = request.getSession().getAttribute("windfoneSessioin");
		if ( sessionObj !=null ) {
			orderList =  (List)sessionObj;
		}
		return SUCCESS;
	}
	
	private void useJdbcMethod(String loginName,String userpassword ){
		String jdbcurl = "jdbc:mysql://121.199.27.232:3306/zp1151_db?useUnicode=true&characterEncoding=UTF-8";
		String user = "zp1151";
		String password = "BaMo78204D4ADCF12";
		String path = ServletActionContext.getServletContext().getRealPath("/");
        path = path.replace("\\", "/")+"WEB-INF/db.properties";
        try { 
    	  InputStream in = new FileInputStream( path);
    	  Properties prop = new Properties(); 
    	  prop.load(in);
    	  jdbcurl = prop.getProperty("jdbc.url");
    	  user = prop.getProperty("jdbc.username");
    	  password = prop.getProperty("jdbc.password");
    	  Class.forName("com.mysql.jdbc.Driver"); 
    	  Connection conn = DriverManager.getConnection(jdbcurl+"&user="+user +"&password="+password);
    	  Statement stmt=conn.createStatement();
    	  
    	  ResultSet rs=stmt.executeQuery("SELECT * FROM  member  WHERE loginName='"+loginName+"'"); 
    	  if ( rs.next()){
    		  System.out.println("has user" );
    	  }else {
    		  rs.close();
    		 String insertSql=" INSERT INTO member (loginName,level,points ,status,password)  VALUES ('"+loginName+"',0,0,1,'"+StringUtil.encode(userpassword)+"')";
    		 stmt.execute(insertSql);
    		 String loadSql = "SELECT * FROM  member  WHERE loginName='"+loginName+"' AND password='"+StringUtil.encode( userpassword )+"'";
    		 rs = stmt.executeQuery(loadSql);
    		 Member to= new Member();
    		 if( rs.next()){
				to.setId(rs.getInt("id"));
				to.setCardId(rs.getString("cardId"));
				to.setLevel(rs.getInt("level"));
				to.setName(rs.getString("name"));
				to.setLoginName(rs.getString("loginName"));
				to.setPoints(rs.getInt("points"));
				to.setPointsb(rs.getInt("pointsb"));
				to.setStatus(rs.getInt("status"));
				to.setCreateTime(rs.getDate("createTime"));
				HttpServletRequest request = ServletActionContext.getRequest();
				HttpSession session = request.getSession();
				session.setAttribute("userBean", to);
//				int i=memberService.updateLastLogin(memberBean);
    	  }
    	  String detailSql =  " INSERT INTO memberdetail (memberId,email,sex)  VALUES ("+to.getId()+",'"+email+"',-1 )";
    	  stmt.execute(detailSql);
    	 }
    	 rs.close();
    	 stmt.close();
    	 conn.close();
      } catch (Exception e) { 
    	  e.printStackTrace(); 
      } 
	}
	
	public List<Order> getOrderList() {
		return orderList;
	}
	public void setOrderList(List<Order> orderList) {
		this.orderList = orderList;
	}
	private List<Order> orderList ;
}
